package cn.itsource.pethome.basic.service.impl;

import cn.itsource.pethome.basic.mapper.BaseMapper;
import cn.itsource.pethome.basic.service.IBaseService;
import cn.itsource.pethome.basic.query.BaseQuery;
import cn.itsource.pethome.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class BaseServiceImpl<T> implements IBaseService<T> {
    @Autowired
    private BaseMapper<T> baseMapper;

    /**
     * 对象添加方法
     *
     * @param t
     */
    @Override
    @Transactional
    public void save(T t) {
        baseMapper.save(t);
    }

    /**
     * 对象修改方法
     *
     * @param t
     */
    @Override
    @Transactional
    public void update(T t) {
        baseMapper.update(t);
    }

    /**
     * 对象删除
     *
     * @param id
     */
    @Override
    @Transactional
    public void delete(Long id) {
        baseMapper.delete(id);
    }

    /**
     * 对象批量删除
     *
     * @param ids
     */
    @Override
    @Transactional
    public void patchDelete(Long[] ids) {
        baseMapper.patchDelete(ids);
    }

    /**
     * 根据id查询对象
     *
     * @param id
     * @return
     */
    @Override
    public T loadById(Long id) {
        return baseMapper.loadById(id);
    }

    /**
     * 查询所有对象
     *
     * @return
     */
    @Override
    public List<T> loadAll() {
        return baseMapper.loadAll();
    }

    /**
     * 根据条件查询 分页数据
     *
     * @param query
     * @return
     */
    @Override
    public PageList<T> loadPageByQuery(BaseQuery query) {
        //根据条件查询总条数
        Long count = baseMapper.findCountByQuery(query);
        //如果获取的条数为0，
        if (count.equals(0L)){
            //直接返回
          return new PageList<>();
        }
        //根据条件获取分页数据
        List<T> result = baseMapper.findByQuery(query);
        //返回数据
        return new PageList<T>(result,count);
    }
}
